package org.ran.demo.http.stream;

import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.TimeUnit;
/**
 * 
 * @author caoran
 *
 */
public class StreamDemo {
    public static void main(String[] args) throws Exception{
        InputStream inputStream = getInmemoryInputStream();
        int b;
        while ((b=inputStream.read())>-1) {
            System.out.print((char)b);
        }
        System.out.println();
        System.out.println("inputStream.read()返回-1，流已关闭");
    }
    
    /**
     * 模拟InputStream
     * @return
     * @throws Exception
     */
    public static InputStream getInmemoryInputStream() throws Exception {
        PipedOutputStream pipedOutputStream = new PipedOutputStream();
        new Thread(()->{
            try {
                int counter=0;
                while (counter<11) {
                    counter++;
                    pipedOutputStream.write((byte)'a');
                    TimeUnit.SECONDS.sleep(1);
                }
                pipedOutputStream.close();
            } catch (Exception e) {
            }
        }).start();
        return new PipedInputStream(pipedOutputStream);
    }
}
